package cn.hiapi.shop.api;

import cn.hiapi.basic.ResponseEntity;
import cn.hiapi.basic.controller.BasicController;
import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.redis.data.LockConst;
import cn.hiapi.basic.security.TokenGet;
import cn.hiapi.basic.token.Token;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.interfaces.ILockService;
import cn.hiapi.interfaces.user.IUserService;
import cn.hiapi.interfaces.user.data.UserDataBase;
import cn.hiapi.shop.entity.shop.ShopLinkUser;
import cn.hiapi.shop.service.shop.ShopLinkUserService;
import cn.hiapi.shopkeeper.consts.AppConst;
import cn.hiapi.user.dto.BasicUser;
import cn.hiapi.user.entity.User;
import cn.hiapi.utils.JsonUtils;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author AdinZ
 * @date 2023/2/9 14:32
 */
@RestController
@RequestMapping("/shop/account")
public class ShopLinkUserController extends BasicController {
    private final DispatchContext dispatchContext;

    public ShopLinkUserController(DispatchContext dispatchContext) {
        this.dispatchContext = dispatchContext;
    }

    @GetMapping("/list")
    public ResponseEntity list(@RequestParam("shopId") long shopId) {
        Token<User> token = TokenGet.get();
        this.dispatchContext.getServiceOne(ShopLinkUserService.class).verifyShop(token.getFid(), shopId);
        List<ShopLinkUser> list = this.dispatchContext.getServiceOne(ShopLinkUserService.class).findList(new QueryWrapper().eq("shopId", shopId), Sort.by(Sort.Direction.DESC, "id"));
        List<JSONObject> collect = list.stream().map(e -> {
            UserDataBase user = this.dispatchContext.getServiceOne(IUserService.class).fieldBase(e.getUid());
            return JsonUtils.builder()
                    .put("id", e.getId())
                    .put("name", e.getName())
                    .put("rid", e.getRid())
                    .put("current", e.getUid() == token.getFid())
                    .put("nickname", user.getNickname())
                    .put("avatar", user.getAvatar())
                    .put("mobile", user.getMobile())
                    .put("username", user.getUsername())
                    .build();
        }).collect(Collectors.toList());
        return toSuccess(collect);
    }

    @ApiOperation(value = "添加账号", notes = "添加账号", nickname = "AdinZ")
    @PostMapping("/add")
    public ResponseEntity addAccount(@RequestBody JSONObject data) {


        long shopId = data.getLongValue("shopId");
        String mobile = data.getString("mobile");
        if (StringUtils.isEmpty(mobile)) {
            return toError("请输入手机号");
        }
        String name = data.getString("name");
        if (StringUtils.isEmpty(name)) {
            return toError("请填写姓名");
        }
        long rid = data.getIntValue("rid");
        if (rid <= 0) return toError("请选择角色");


        String lock = LockConst.getLock("add-account", shopId);
        try {
            this.dispatchContext.getServiceOne(ILockService.class).lockThr(lock);
            Token<Object> token = TokenGet.get();
            this.dispatchContext.getServiceOne(ShopLinkUserService.class).verifyShop(token.getFid(), shopId, AppConst.SHOP_ROLE_ACCOUNT);
            Long uid = this.dispatchContext.getServiceOne(IUserService.class).getUid(token.getMerchantId(), mobile);
            if (uid == null) return toError("本手机号先进行登录");
            ShopLinkUser user = this.dispatchContext.getServiceOne(ShopLinkUserService.class).get(uid, shopId);
            if (user != null) return toError("本手机号已经存在了");

            user = new ShopLinkUser();
            user.setUid(uid);
            user.setName(name);
            user.setShopId(shopId);
            user.setRid(rid);
            this.dispatchContext.getServiceOne(ShopLinkUserService.class).save(user);
            return toSuccess();
        } finally {
            this.dispatchContext.getServiceOne(ILockService.class).unlock(lock);
        }


    }

    @ApiOperation(value = "添加账号", notes = "添加账号", nickname = "AdinZ")
    @PostMapping("/edit")
    public ResponseEntity editAccount(@RequestBody JSONObject data) {
        long shopId = data.getLongValue("shopId");
        String name = data.getString("name");
        long id = data.getLongValue("id");
        if (StringUtils.isEmpty(name)) {
            return toError("请填写姓名");
        }
        Token<Object> token = TokenGet.get();
        this.dispatchContext.getServiceOne(ShopLinkUserService.class).verifyShop(token.getFid(), shopId, AppConst.SHOP_ROLE_ACCOUNT);

        ShopLinkUser user = this.dispatchContext.getServiceOne(ShopLinkUserService.class).get(id);
        if (user == null || user.getShopId() != shopId) return toError("账号不存在");
        user.setName(name);
        this.dispatchContext.getServiceOne(ShopLinkUserService.class).save(user);
        return toSuccess();
    }

    @ApiOperation(value = "删除账号",notes = "删除账号",nickname = "AdinZ" )
    @GetMapping("/delete")
    public ResponseEntity deleteAccount(@RequestParam("shopId")long shopId,@RequestParam("id")long id){
        Token<Object> token = TokenGet.get();
        this.dispatchContext.getServiceOne(ShopLinkUserService.class).verifyShop(token.getFid(), shopId, AppConst.SHOP_ROLE_ACCOUNT);
        ShopLinkUser user = this.dispatchContext.getServiceOne(ShopLinkUserService.class).get(id);
        if (user == null || user.getShopId() != shopId) return toError("账号不存在");
        if(user.getRid()==0)return toError("无法删除超级管理员");
        this.dispatchContext.getServiceOne(ShopLinkUserService.class).delete(user);
        return toSuccess();
    }

}
